/**
 * WebSocket 工厂模块
 * WebSocket Factory Module
 * 
 * 实现单例模式的 WebSocketManager，确保全应用只有一个 WebSocket 连接实例
 * 避免重复连接、资源浪费和消息重复问题
 */

import { WebSocketConfig, getMarketDataWebSocketConfig } from './config';
import type { WebSocketManager, WebSocketCallbacks, WebSocketMessage, WebSocketManagerConfig } from './WebSocketManager';

/**
 * WebSocket 实例缓存
 * 使用 path 作为 key，确保同一路径只有一个实例
 */
const wsManagerCache = new Map<string, WebSocketManager>();

/**
 * 转换 WebSocketConfig 到 WebSocketManagerConfig
 * 处理字段名差异（reconnectDelay -> reconnectInterval）
 */
function convertConfig(config: WebSocketConfig): WebSocketManagerConfig {
  return {
    url: config.url,
    reconnectInterval: config.reconnectDelay,
    maxReconnectAttempts: config.maxReconnectAttempts,
    heartbeatInterval: config.heartbeatInterval,
    timeout: config.connectionTimeout,
  };
}

/**
 * 获取或创建 WebSocketManager 实例（单例模式）
 * 
 * @param config WebSocket 配置
 * @param callbacks WebSocket 回调函数
 * @returns WebSocketManager 实例
 */
export async function getWebSocketManager(
  config: WebSocketConfig,
  callbacks?: WebSocketCallbacks
): Promise<WebSocketManager> {
  // 使用 URL 作为缓存 key
  const cacheKey = config.url;

  // 检查缓存中是否已存在实例
  let manager = wsManagerCache.get(cacheKey);

  if (manager) {
    // 实例已存在，检查连接状态
    console.log(`[WebSocket Factory] 复用已存在的 WebSocket 实例: ${cacheKey}`);
    
    // 如果提供了新的回调，更新回调
    if (callbacks) {
      console.warn(`[WebSocket Factory] 检测到重复初始化，建议检查代码避免多次调用`);
      // 注意：这里可能需要实现回调的合并或替换逻辑
    }
    
    return manager;
  }

  // 创建新实例
  console.log(`[WebSocket Factory] 创建新的 WebSocket 实例: ${cacheKey}`);
  
  // 动态导入 WebSocketManager
  const { WebSocketManager: WSManager } = await import('./WebSocketManager');
  
  // 转换配置格式
  const managerConfig = convertConfig(config);
  manager = new WSManager(managerConfig, callbacks);

  // 缓存实例
  wsManagerCache.set(cacheKey, manager);

  // 监听连接关闭事件，自动清理缓存
  const originalOnDisconnect = callbacks?.onDisconnect;
  if (manager && typeof (manager as any).addEventListener === 'function') {
    // 如果 WebSocketManager 支持事件监听
    (manager as any).addEventListener('close', () => {
      console.log(`[WebSocket Factory] 连接关闭，清理缓存: ${cacheKey}`);
      wsManagerCache.delete(cacheKey);
    });
  }

  return manager;
}

/**
 * 获取市场数据 WebSocketManager 实例（单例模式）
 * 专门用于市场数据的便捷方法
 * 
 * @param callbacks WebSocket 回调函数
 * @param userConfig 用户自定义配置（可选）
 * @returns WebSocketManager 实例
 */
export async function getMarketDataWebSocketManager(
  callbacks?: WebSocketCallbacks,
  userConfig?: Partial<WebSocketConfig>
): Promise<WebSocketManager> {
  const config = getMarketDataWebSocketConfig(userConfig);
  return getWebSocketManager(config, callbacks);
}

/**
 * 销毁指定的 WebSocketManager 实例
 * 
 * @param url WebSocket URL
 */
export function destroyWebSocketManager(url: string): void {
  const manager = wsManagerCache.get(url);
  
  if (manager) {
    console.log(`[WebSocket Factory] 销毁 WebSocket 实例: ${url}`);
    
    // 断开连接
    if (typeof (manager as any).disconnect === 'function') {
      (manager as any).disconnect();
    }
    
    // 从缓存中移除
    wsManagerCache.delete(url);
  }
}

/**
 * 销毁所有 WebSocketManager 实例
 * 用于应用卸载或重置场景
 */
export function destroyAllWebSocketManagers(): void {
  console.log(`[WebSocket Factory] 销毁所有 WebSocket 实例 (共 ${wsManagerCache.size} 个)`);
  
  wsManagerCache.forEach((manager, url) => {
    if (typeof (manager as any).disconnect === 'function') {
      (manager as any).disconnect();
    }
  });
  
  wsManagerCache.clear();
}

/**
 * 获取当前活跃的 WebSocket 连接数量
 * 用于监控和调试
 */
export function getActiveWebSocketCount(): number {
  return wsManagerCache.size;
}

/**
 * 获取所有活跃的 WebSocket 连接信息
 * 用于监控和调试
 */
export function getActiveWebSockets(): Array<{ url: string; connected: boolean }> {
  const result: Array<{ url: string; connected: boolean }> = [];
  
  wsManagerCache.forEach((manager, url) => {
    // 尝试获取连接状态
    let connected = false;
    if (typeof (manager as any).isConnected === 'function') {
      connected = (manager as any).isConnected();
    } else if ((manager as any).connected !== undefined) {
      connected = (manager as any).connected;
    }
    
    result.push({ url, connected });
  });
  
  return result;
}

/**
 * 导出工厂单例实例（用于高级场景）
 */
export const WebSocketFactory = {
  getManager: getWebSocketManager,
  getMarketDataManager: getMarketDataWebSocketManager,
  destroy: destroyWebSocketManager,
  destroyAll: destroyAllWebSocketManagers,
  getActiveCount: getActiveWebSocketCount,
  getActiveList: getActiveWebSockets,
};

/**
 * 默认导出
 */
export default WebSocketFactory;

